package com.lhj.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhj.reggie.common.CustomException;
import com.lhj.reggie.common.R;
import com.lhj.reggie.entity.Category;
import com.lhj.reggie.entity.Dish;
import com.lhj.reggie.entity.Setmeal;
import com.lhj.reggie.mapper.CategoryMapper;
import com.lhj.reggie.mapper.DishMapper;
import com.lhj.reggie.mapper.SetmealMapper;
import com.lhj.reggie.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SetmealMapper setmealMapper;

    @Resource
    private DishMapper dishMapper;


    public R<String> insert( Category category) {
        categoryMapper.insert(category);
        return R.success("新增分类成功");
    }


    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> page1 = new Page(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加排序
        lqw.orderByAsc(Category::getSort);
        //执行查询
        categoryMapper.selectPage(page1, lqw);
        return R.success(page1);
    }


    public R<String> remove(Long ids) {
        //判断分类有无关联菜品
        //条件构造器
        LambdaQueryWrapper<Dish> DishLqw = new LambdaQueryWrapper<>();
        //添加条件
        DishLqw.eq(Dish::getCategoryId, ids);
        int count = dishMapper.selectCount(DishLqw);
        if (count > 0) {
            //抛出异常
            throw new CustomException("当前分类关联了菜品，不能删除");
        }
        //判断分类有无关联套餐
        //条件构造器
        LambdaQueryWrapper<Setmeal> SetmealLqw = new LambdaQueryWrapper<>();
        //添加条件
        SetmealLqw.eq(Setmeal::getCategoryId, ids);
        int count1 = setmealMapper.selectCount(SetmealLqw);
        if (count1 > 0) {
            //抛出异常
            throw new CustomException("当前分类关联了套餐，不能删除");
        }
        categoryMapper.deleteById(ids);
        return R.success("删除分类信息成功");
    }


    public R<String> update( Category category) {
        categoryMapper.updateById(category);
        return R.success("修改分类信息成功");
    }


    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //条件
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryMapper.selectList(lqw);
        return R.success(list);
    }
}
